/**
 * @description address controller
 * @author boen
 */

const Address = require('../models/Address')

/**
 * 创建收货地址
 * @param {string} username 用户名
 * @param {Object} data 地址的详细信息
 * @returns 
 */
async function createAddress(username,data) {
    const newAddress = await Address.create({
        username,
        ...data
    })
    return newAddress
}

/**
 * 获取收货地址列表
 * @param {string} username 用户名
 * @returns 
 */
async function getAddressList(username) {
    const addressList = await Address.find({
        username
    }).sort({ updatedAt: -1 })
    return addressList
}

/**
 * 根据id查找单个收货地址
 * @param {string} id id
 * @returns 
 */
async function getAddressById(id) {
    const address = await Address.findById(id)
    return address
}

/**
 * 根据id更新收货地址
 * @param {string} id id
 * @param {string} username 用户名
 * @param {Object} data data
 * @returns 
 */
async function updateAddressById(id,username,data) {
    const address = await Address.findOneAndUpdate({
            _id: id,
            username
    },data, {
        new: true
    })
    return address
}

module.exports = {
    createAddress,
    getAddressList,
    getAddressById,
    updateAddressById
}